/* eslint-disable react/prop-types */
import React, { useState, useEffect, useRef } from 'react';
import './TabComponent.css';


const TabComponent = ({ tabs, autoSwitchInterval = 5000 }) => {
    // 定义当前激活的 Tab 索引和进度条进度
    const [activeTabIndex, setActiveTabIndex] = useState(0);
    const [progress, setProgress] = useState(0);
    // 定义一个 ref 来存储自动切换的定时器
    const intervalRef = useRef(null);

    // 处理 Tab 点击事件
    const handleTabClick = (index) => {
        // 设置当前激活的 Tab 索引
        setActiveTabIndex(index);
        // 重置进度条进度
        setProgress(0);
        // 清除自动切换的定时器
        clearInterval(intervalRef.current);
        // 开始自动切换
        startAutoSwitch();
    };

    // 开始自动切换
    const startAutoSwitch = () => {
        // 设置自动切换的定时器
        intervalRef.current = setInterval(() => {
            // 更新进度条进度
            setProgress((prevProgress) => {
                // 如果进度条进度达到 100，则切换到下一个 Tab
                if (prevProgress >= 100) {
                    setActiveTabIndex((prevIndex) => (prevIndex + 1) % tabs.length);
                    return 0;
                }
                // 否则，进度条进度加 1
                return prevProgress + 1;
            });
        }, autoSwitchInterval / 100);
    };

    // 组件挂载时开始自动切换
    useEffect(() => {
        // 开始自动切换
        startAutoSwitch();
        // 组件卸载时清除定时器
        return () => {
            clearInterval(intervalRef.current);
        };
    }, []);

    return (
        <div className="tab-container">
            <div className="tab-header">
                {tabs.map((tab, index) => (
                    <div
                        key={index}
                        className={`tab-item ${index === activeTabIndex ? 'active' : ''}`}
                        onClick={() => handleTabClick(index)}
                    >
                        {tab.title}
                        {index === activeTabIndex && (
                            <div className="progress-bar">
                                <div
                                    className="progress"
                                    style={{ width: `${progress}%` }}
                                ></div>
                            </div>
                        )}
                    </div>
                ))}
            </div>
            <div className="tab-content">
                {tabs[activeTabIndex].content}
            </div>
        </div>
    );
};

export default TabComponent;